package com.cloud.media.api.web;

import java.io.File;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.cloud.media.api.entity.Media;
import com.cloud.media.api.service.MediaService;
import com.cloud.media.common.consts.MediaConsts;
import com.cloud.media.common.exception.BizException;
import com.cloud.media.common.result.Quokka;
import com.cloud.media.common.utils.SessionHelper;
import com.cloud.media.common.utils.WordHelper;
import com.cloud.media.interfaces.FeignClientSystem;

@RestController
@RequestMapping("media/api")
public class MediaController {

	private static final Logger logger = LoggerFactory.getLogger(MediaController.class);

	@Autowired
	private MediaService mediaService;

	@Autowired
	private FeignClientSystem feignClientSystem;

	@PostMapping("/upload")
	public Quokka upload( MultipartFile file, String mediaCatalog) {
		String mediaRootPath = feignClientSystem.getMediaRootPath(MediaConsts.DEFAULT_MEDIA_ROOT_PATH_CONFIG,
				MediaConsts.DEFAULT_MEIDA_ROOT);
		return new Quokka(true, mediaService.upload(file, mediaRootPath, mediaCatalog));
	}

	@GetMapping("/get/{mediaId}")
	public ResponseEntity<byte[]> get(@PathVariable("mediaId") long mediaId) throws Exception {
		HttpHeaders headers = new HttpHeaders();
		Media media = mediaService.loadMedia(mediaId);
		String fileName = new String(media.getMediaName().getBytes("ISO8859-1"), "UTF-8");
		headers.add("Content-Disposition", "attachment;filename=" + fileName);
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		String mediaRootPath = feignClientSystem.getMediaRootPath(MediaConsts.DEFAULT_MEDIA_ROOT_PATH_CONFIG,
				MediaConsts.DEFAULT_MEIDA_ROOT);
		return new ResponseEntity<byte[]>(
				FileUtils.readFileToByteArray(new File(mediaRootPath + File.separator + media.getMediaPath())), headers,
				HttpStatus.OK);
	}

	@GetMapping("/avatar")
	public Quokka getAvatar(long id) throws Exception {
		if (0 == id) {
			id = SessionHelper.get().getHumanId();
		}
		String mediaRootPath = feignClientSystem.getMediaRootPath(MediaConsts.DEFAULT_MEDIA_ROOT_PATH_CONFIG,
				MediaConsts.DEFAULT_MEIDA_ROOT);
		// 检查文件是否存在，存在则读取文件，不存在则取默认头像
		StringBuilder basePath = new StringBuilder(mediaRootPath).append(File.separator)
				.append(MediaConsts.MEDIA_CATALOG_AVATAR).append(File.separator);
		byte[] fileBytes = null;
		File f = new File(basePath.toString() + id + ".jpg");
		if (f.exists()) {
			fileBytes = FileUtils.readFileToByteArray(f);
			return new Quokka(true, Base64.getEncoder().encodeToString(fileBytes));
		}
		return new Quokka(true);
	}

	@PostMapping("/uploadavatar")
	public Quokka uploadAvatar(MultipartFile file, long id) throws Exception {
		// 人员头像，不入库，直接存为人员对应的id
		if (0 == id) {
			id = SessionHelper.get().getHumanId();
		}
		String mediaRootPath = feignClientSystem.getMediaRootPath(MediaConsts.DEFAULT_MEDIA_ROOT_PATH_CONFIG,
				MediaConsts.DEFAULT_MEIDA_ROOT);
		File f = new File(
				mediaRootPath + File.separator + MediaConsts.MEDIA_CATALOG_AVATAR + File.separator + id + ".jpg");
		FileUtils.writeByteArrayToFile(f, file.getBytes());
		return new Quokka(true, Base64.getEncoder().encodeToString(file.getBytes()));
	}

	@GetMapping("/detail/{id}")
	public Quokka loadDetail(@PathVariable("id") long id) throws Exception {
		Media media = mediaService.loadMedia(id);
		String mediaWebPath = feignClientSystem.getMediaRootPath(MediaConsts.DEFAULT_MEDIA_WEB_PATH_CONFIG, "");
		if (StringUtils.isEmpty(mediaWebPath)) {
			throw new BizException("缺少文件访问前缀配置项：DEFAULT_MEDIA_WEB_PATH_CONFIG");
		}
		Map<String, Object> map = new HashMap<String, Object>();
		if (MediaConsts.MEDIA_TYPE_DOC.equals(media.getMediaType())
				|| MediaConsts.MEDIA_TYPE_DOCX.equals(media.getMediaType())) {
			String mediaRootPath = feignClientSystem.getMediaRootPath(MediaConsts.DEFAULT_MEDIA_ROOT_PATH_CONFIG,
					MediaConsts.DEFAULT_MEIDA_ROOT);
			byte[] fileBytes = WordHelper.convertWord2PDF(
					FileUtils.readFileToByteArray(new File(mediaRootPath + File.separator + media.getMediaPath())));
			map.put("content", Base64.getEncoder().encodeToString(fileBytes));
		}
		String mediaPath = media.getMediaPath().replaceAll("\\\\", "/");
		media.setMediaPath(mediaWebPath + "/" + mediaPath);
		map.put("media", media);
		Quokka result = new Quokka(true, map);
		return result;
	}

	/**
	 * 获取图片路径
	 * 
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/getAvatarUrl")
	public Quokka getAvatarUrl(long id) throws Exception {
		if (0 == id) {
			id = SessionHelper.get().getHumanId();
		}
		logger.debug("getAvatarUrl start -->" + System.currentTimeMillis());
		String mediaRootPath = feignClientSystem.getMediaRootPath(MediaConsts.DEFAULT_MEDIA_ROOT_PATH_CONFIG,
				MediaConsts.DEFAULT_MEIDA_ROOT);
		// 检查文件是否存在，存在则读取文件，不存在则取默认头像
		String basePath = mediaRootPath + File.separator + MediaConsts.MEDIA_CATALOG_AVATAR + File.separator;
		File f = new File(basePath + id + ".jpg");
		if (f.exists()) {
			String mediaWebPath = feignClientSystem.getMediaRootPath(
					MediaConsts.DEFAULT_MEDIA_WEB_PATH_CONFIG, "");
			logger.debug("mediaWebPath-->" + mediaWebPath);
			String webPath = mediaWebPath + File.separator + MediaConsts.MEDIA_CATALOG_AVATAR + File.separator;
			logger.debug("webPath-->" + webPath);
			return new Quokka(true, webPath + id + ".jpg");
		}
		return new Quokka(true);
	}

	/**
	 * 公告消息获取链接。
	 * @param ids
	 * @return
	 */
	@RequestMapping("geturlbyid")
	public Quokka getUrlById(@RequestBody List<Long> ids) {
		return new Quokka(true, mediaService.getUrlById(ids));
	}

	/** 资料库加载 */
	@RequestMapping("fileinfo")
	public Quokka getFileInfo() {
		return new Quokka(true, mediaService.getFileInfo());
	}
}
